import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper_app/components/windows/window_title_bar.dart';
import 'package:wallpaper_app/themes/theme_provider.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart'; // 添加颜色选择器库

class ThemePage extends StatefulWidget {
  const ThemePage({super.key});

  @override
  State<ThemePage> createState() => _ThemePageState();
}

class _ThemePageState extends State<ThemePage> {
  double radius = 5;
  Color _currentColor = Colors.blueAccent;

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      body: Consumer<ThemeProvider>(
        builder: (context, provider, child) => Column(
          children: [
            WindowTitleBar(isBack: true),
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(8),
                child: Column(
                  children: [
                    _buildSection('主题设置', _buildThemeOptions(provider)),
                    _buildSection('主题色', _buildColorOptions(provider)),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSection(String title, Widget content) {
    final theme = Theme.of(context).colorScheme;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: double.infinity,
          padding: EdgeInsets.all(8),
          margin: EdgeInsets.symmetric(vertical: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(radius),
            color: theme.primaryContainer,
          ),
          child: Text(
            title,
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
        ),
        content,
      ],
    );
  }

  Widget _buildThemeOptions(ThemeProvider provider) {
    return Column(
      children: [
        _buildThemeOption(
          title: '浅色主题',
          isSelected: !provider.isDarkMode && !provider.followSystem,
          onTap: provider.setLightTheme,
        ),
        SizedBox(height: 8),
        _buildThemeOption(
          title: '暗色主题',
          isSelected: provider.isDarkMode && !provider.followSystem,
          onTap: provider.setDarkTheme,
        ),
        SizedBox(height: 8),
        _buildThemeOption(
          title: '跟随系统',
          isSelected: provider.followSystem,
          onTap: provider.setFollowSystem,
        ),
      ],
    );
  }

  Widget _buildThemeOption({
    required String title,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    final theme = Theme.of(context).colorScheme;
    return Material(
      borderRadius: BorderRadius.circular(radius),
      clipBehavior: Clip.antiAlias,
      color: theme.primaryContainer,
      child: InkWell(
        onTap: onTap,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          child: Row(
            children: [
              Radio(
                value: isSelected,
                groupValue: true,
                onChanged: (_) => onTap(),
              ),
              Text(title),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildColorOptions(ThemeProvider provider) {
    final List<Map<String, dynamic>> colors = [
      {'color': Colors.lightBlueAccent, 'name': '浅蓝色'},
      {'color': Colors.blueAccent, 'name': '蓝色'},
      {'color': Colors.purpleAccent, 'name': '紫色'},
      {'color': Colors.deepPurpleAccent, 'name': '深紫色'},
      {'color': Colors.green, 'name': '绿色'},
      {'color': Colors.deepOrangeAccent, 'name': '橙色'},
      {'color': Colors.deepOrange, 'name': '深橙色'},
      {'color': Colors.redAccent, 'name': '红色'},
      {'color': Colors.pinkAccent, 'name': '粉色'},
      {'color': Colors.brown, 'name': '棕色'},
      {'color': Colors.blueGrey, 'name': '灰蓝色'},
      {'color': Colors.grey, 'name': '灰色'},
    ];

    // 使用屏幕宽度除以 80 来计算每行显示的颜色项数量
    final double screenWidth = MediaQuery.of(context).size.width;
    final int crossAxisCount = (screenWidth / 80).floor();

    return GridView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(), // 内部不滚动
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount, // 设置每行显示4个颜色项
      ),
      itemCount: colors.length + 1, // 加上自定义颜色选择器
      itemBuilder: (context, index) {
        if (index == colors.length) {
          return Padding(
            padding: const EdgeInsets.all(5),
            child: _buildCustomColorPicker(provider),
          );
        }
        return Padding(
          padding: const EdgeInsets.all(5),
          child: _buildColorItem(
            color: colors[index]['color'],
            name: colors[index]['name'],
            onTap: () => provider.setCustomTheme(colors[index]['color']),
          ),
        );
      },
    );
  }

  Widget _buildColorItem({
    required Color color,
    required String name,
    required VoidCallback onTap,
  }) {
    return SizedBox(
      width: 60,
      height: 60,
      child: Material(
        color: color,
        borderRadius: BorderRadius.circular(radius),
        child: InkWell(
          onTap: onTap,
          child: Center(
            child: Text(
              name,
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCustomColorPicker(ThemeProvider provider) {
    return SizedBox(
      width: 60,
      height: 60,
      child: Material(
        color: Colors.grey,
        borderRadius: BorderRadius.circular(radius),
        child: InkWell(
          onTap: () => _showColorPicker(provider),
          child: Center(
            child: Icon(
              Icons.color_lens_outlined,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

  void _showColorPicker(ThemeProvider provider) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('选择自定义颜色'),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(radius),
        ),
        content: SingleChildScrollView(
          child: ColorPicker(
            pickerColor: _currentColor,
            onColorChanged: (color) => setState(() => _currentColor = color),
          ),
        ),
        actions: [
          TextButton(
            child: Text('确定'),
            onPressed: () {
              provider.setCustomTheme(_currentColor);
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }
}
